﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;
using SGLLv2.UI.Properties;

namespace SGLLv2.UI
{
    public partial class FormServices : Template.FormTemplate, IMethods
    {
        private enum Mode
        {
            Increment = 1,
            Decrement = -1
        }

        // Declare Global Variables
        private MDIParent mdiParent;

        readonly DataGridViewCellStyle _cellstyleVoid = new DataGridViewCellStyle();
        readonly DataGridViewCellStyle _cellstyleNormal = new DataGridViewCellStyle();
        readonly DataGridViewCellStyle _cellstyleAlternative = new DataGridViewCellStyle();

        // Class Constructor
        public FormServices()
        {
            InitializeComponent();
        }

        // Form
        private void FormServices_Load(object sender, EventArgs e)
        {
            // Declare Local Variables
            mdiParent = (MDIParent)(ParentForm);
            if (mdiParent == null) return;

            // Set cell style for void transactions on Grid.
            _cellstyleVoid.BackColor = Settings.Default.RequiedFieldForecolor;
            _cellstyleVoid.ForeColor = Color.White;
            _cellstyleVoid.SelectionForeColor = Color.White;
            _cellstyleVoid.SelectionBackColor = Color.DarkRed;
            _cellstyleVoid.Font = Settings.Default.AppFontSmallBody;

            _cellstyleNormal.BackColor = Color.White;
            _cellstyleNormal.ForeColor = Settings.Default.AppForecolor;
            _cellstyleNormal.SelectionBackColor = Settings.Default.AppForecolor;
            _cellstyleNormal.SelectionForeColor = Color.White;
            _cellstyleNormal.Font = Settings.Default.AppFontSmallBody;

            _cellstyleAlternative.BackColor = Color.Gainsboro;
            _cellstyleAlternative.ForeColor = Settings.Default.AppForecolor;
            _cellstyleAlternative.SelectionBackColor = Settings.Default.AppForecolor;
            _cellstyleAlternative.SelectionForeColor = Color.White;
            _cellstyleAlternative.Font = Settings.Default.AppFontSmallBody;

            //Build a list
            var dataSource = new List<TransactionType>
                                 {
                                     new TransactionType {Key = Global.TransactionTypes.DepositReceipt, Value = Resources.comboBoxTransactionTypeDepositReceipt},
                                     new TransactionType {Key = Global.TransactionTypes.ProofOfPayment, Value = Resources.comboBoxTransactionTypeProofOfPayment},
                                     new TransactionType {Key = Global.TransactionTypes.ProcessOrder, Value = Resources.comboBoxTransactionTypeProcessOrder}
                                 };

            //Setup data binding
            comboBoxTransactionType.DataSource = dataSource;
            comboBoxTransactionType.DisplayMember = "Value";
            comboBoxTransactionType.ValueMember = "Key";

            try
            {
                // Fill out each dataset.
                sP_USERS_SELECTTableAdapter.Fill(dataSetSGLL.SP_USERS_SELECT);
                sP_ROUTES_SELECTTableAdapter.Fill(dataSetSGLL.SP_ROUTES_SELECT);

                foreach (var messenger in SP_MESSENGERS_SELECTTableAdapter.GetDataByActives())
                {
                    comboBoxFilterMessenger.Items.Add(messenger.Código);
                }
                //foreach (var checkbox in comboBoxFilterMessenger.)

                // Clear form
                ClearForm();

                // Setting up limits on Date Time picker.
                var minServicesDate = queriesTableAdapter.GetMinServicesDate();
                if (minServicesDate != null)
                    dateTimePickerFilterStart.MinDate = (DateTime)minServicesDate;
                else
                    dateTimePickerFilterStart.MinDate = DateTime.Now;

                // Adding the amount of minutes that has a day minus one.
                dateTimePickerFilterEnd.MaxDate = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, 23, 59, 59);

                // Setting up initial values on both date time pickers.
                dateTimePickerFilterStart.Value = new DateTime(dateTimePickerFilterEnd.MaxDate.Year, dateTimePickerFilterEnd.MaxDate.Month, dateTimePickerFilterEnd.MaxDate.Day, 0, 0, 0);
                dateTimePickerFilterEnd.Value = dateTimePickerFilterEnd.MaxDate;

                // Show Services
                refreshServices();

                // Prevent from calling future times the Call Form
                mdiParent.toolStripMenuItemServices.Enabled = mdiParent.toolStripButtonServices.Enabled = false;

                // Hooking Up Events
                dataGridView.CellValueChanged += dataGridView_CellValueChanged;
                comboBoxTransactionType.SelectedIndexChanged += comboBoxTransactionType_SelectedIndexChanged;
                comboBoxMessenger.SelectedIndexChanged += comboBoxMessenger_SelectedIndexChanged;
                //comboBoxMessengerFilter.SelectedIndexChanged += comboBoxMessengerFilter_SelectedIndexChanged;
                dateTimePickerFilterStart.ValueChanged += dateTimePickerFilterStart_ValueChanged;
                dateTimePickerFilterEnd.ValueChanged += dateTimePickerFilterEnd_ValueChanged;
                //dataGridViewSummary.RowEnter += dataGridViewSummary_RowEnter;
                //dataGridViewSummary.SelectionChanged += dataGridViewSummary_SelectionChanged;
            }
            catch (Exception exception)
            {
                // Report Error
                mdiParent.SetMessage(MDIParent.MessageType.Error, exception.Message);
                Utilities.ExceptionManager(exception);
            }
        }
        private void FormServices_FormClosing(object sender, FormClosingEventArgs e)
        {
            // Validation
            if (dataGridView.Rows.Count.Equals(0)) return;

            // Let the user know whats going on.
            MessageBox.Show(
                string.Format("No puede salir del Módulo de Servicios hasta que no guarde o elimine todas las transacciones digitadas del mensajero: {0}", comboBoxMessenger.Text),
                Global.AppFullName, MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);

            // Cancel Closing
            e.Cancel = true;
        }

        // Text Box
        private void textBoxComments_KeyDown(object sender, KeyEventArgs e)
        {
            // Validate if is F5 Key.
            if (!e.KeyCode.Equals(Keys.F5)) return;

            // Add date time to the comment textbox.
            if ((textBoxComments.Text.Length + DateTime.Now.ToString(CultureInfo.InvariantCulture).Length) >= textBoxComments.MaxLength) return;
            textBoxComments.Text += string.Concat(DateTime.Now, " ");
            textBoxComments.SelectionStart = textBoxComments.Text.Length;
        }

        // Combo Boxes
        private void comboBoxMessenger_DropDown(object sender, EventArgs e)
        {
            // Populate the Drop Down Box with data.
            mESSENGERS_SELECTABLETableAdapter.Fill(dataSetSGLL.MESSENGERS_SELECTABLE);

            // Reset Drop Down Box Selection.
            comboBoxMessenger.SelectedIndex = -1;
        }
        private void comboBoxMessenger_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Release the Messenger
            if (comboBoxMessenger.Tag != null) queriesTableAdapter.UpdateLockOnOneMessenger(false, null, null, null, comboBoxMessenger.Tag.ToString());

            if (comboBoxMessenger.SelectedIndex.Equals(-1))
            {
                // Disable the Input Control Group Box
                groupBoxInputControl.Enabled = false;
            }
            else
            {
                // Save Selected Messenger
                comboBoxMessenger.Tag = comboBoxMessenger.Text;

                // Lock the Messenger
                queriesTableAdapter.UpdateLockOnOneMessenger(true, DateTime.Now, Environment.UserName, Environment.MachineName, comboBoxMessenger.Text);

                // Enable the Input Control Group Box
                groupBoxInputControl.Enabled = true;
            }

            // Enable Save Button
            enableButtonSave();
        }
        private void comboBoxTransactionType_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Change Combo Box Messenger State
            enableComboBoxMessenger();

            try
            {
                if (comboBoxTransactionType.SelectedIndex.Equals(-1))
                {
                    buttonAccept.Enabled = numericUpDownAmount.Enabled = false;
                    labelSequenceValue.Text = string.Empty;
                    numericUpDownAmount.Value = numericUpDownAmount.Minimum;
                }
                else
                {
                    buttonAccept.Enabled = numericUpDownAmount.Enabled = true;
                    labelSequenceValue.Text = string.Format("{0:00000}", queriesTableAdapter.GetMessengerSequence(comboBoxMessenger.Text, Convert.ToInt32(comboBoxTransactionType.SelectedValue)));
                    numericUpDownAmount.Focus();
                }
            }
            catch (Exception exception)
            {
                // Report Error
                mdiParent.SetMessage(MDIParent.MessageType.Error, exception.Message);
                Utilities.ExceptionManager(exception);
            }
        }
        private void comboBoxForm_SelectionChangeCommitted(object sender, EventArgs e)
        {
            // Enable Save Button
            enableButtonSave();
        }
        private void comboBoxFilterMessenger_CheckBoxCheckedChanged(object sender, EventArgs e)
        {
            refreshServices();
        }
        private void comboBoxFilterMessenger_KeyDown(object sender, KeyEventArgs e)
        {
            // Validations if is Delete Key.
            if (e.KeyCode.Equals(Keys.A))
            {
                // Deactivate Event Handler 
                comboBoxFilterMessenger.CheckBoxCheckedChanged -= comboBoxFilterMessenger_CheckBoxCheckedChanged;

                // Loop throw all the Checkboxes
                foreach (var checkbox in comboBoxFilterMessenger.CheckBoxItems)
                {
                    checkbox.Checked = true;
                }

                // Activate Event Handler
                comboBoxFilterMessenger.CheckBoxCheckedChanged -= comboBoxFilterMessenger_CheckBoxCheckedChanged;

                // Refresh Services
                refreshServices();
            }

            if (e.KeyCode.Equals(Keys.Delete))
            {
                // Deactivate Event Handler 
                comboBoxFilterMessenger.CheckBoxCheckedChanged -= comboBoxFilterMessenger_CheckBoxCheckedChanged;

                // Loop throw all the Checkboxes
                foreach (var checkbox in comboBoxFilterMessenger.CheckBoxItems)
                {
                    checkbox.Checked = false;
                }

                // Activate Event Handler
                comboBoxFilterMessenger.CheckBoxCheckedChanged -= comboBoxFilterMessenger_CheckBoxCheckedChanged;

                // Refresh Services
                refreshServices();
            }
        }
        private void comboBoxForm_KeyDown(object sender, KeyEventArgs e)
        {
            // Validations if is Delete Key.
            if (!e.KeyCode.Equals(Keys.Delete)) return;

            // Declare Local Variable
            ComboBox comboBox = sender as ComboBox;

            // Check is is null.
            if (comboBox != null) comboBox.SelectedIndex = -1;
        }

        // Numeric Up Down
        private void numericUpDownAmount_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode.Equals(Keys.Enter)) buttonAccept_Click(null, null);
        }

        // Date Time Pickers
        private void dateTimePickerFilterStart_ValueChanged(object sender, EventArgs e)
        {
            // Avoid overlap in dates.
            dateTimePickerFilterEnd.MinDate = dateTimePickerFilterStart.Value;

            refreshServices();
        }
        private void dateTimePickerFilterEnd_ValueChanged(object sender, EventArgs e)
        {
            // Avoid overlap in dates.
            dateTimePickerFilterStart.MaxDate = dateTimePickerFilterEnd.Value;

            refreshServices();
        }

        // Buttons
        private void buttonAccept_Click(object sender, EventArgs e)
        {
            // Adding data to the grid.
            dataGridView.Rows.Add(comboBoxTransactionType.SelectedValue, comboBoxTransactionType.Text, labelSequenceValue.Text, numericUpDownAmount.Value, false);

            // Increment Sequence
            updateSequences(comboBoxMessenger.Text, (Global.TransactionTypes)comboBoxTransactionType.SelectedValue, Mode.Increment);

            // Change Combo Box Messenger State
            enableComboBoxMessenger();

            // Clear Entry Control for next input.
            dataGridView.ClearSelection();
            numericUpDownAmount.Value = numericUpDownAmount.Minimum;
            comboBoxTransactionType_SelectedIndexChanged(null, null);
        }
        private void buttonDelete_Click(object sender, EventArgs e)
        {
            // Validations
            if (dataGridView.CurrentRow == null) return;
            if (MessageBox.Show(string.Format("¿Esta seguro que desea eliminar esta transacción del tipo: {0} y secuencia {1}?", dataGridView[dataGridViewTextBoxColumnTransactionType.Index, dataGridView.CurrentRow.Index].Value, dataGridView[DataGridViewTextBoxColumnSequence.Index, dataGridView.CurrentRow.Index].Value), Global.AppFullName, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2).Equals(DialogResult.No)) return;

            // Decrement Sequence
            updateSequences(comboBoxMessenger.Text, (Global.TransactionTypes)dataGridView[DataGridViewTextBoxColumnTransactionTypeKey.Index, dataGridView.CurrentRow.Index].Value, Mode.Decrement);

            // Enable ComboBox Messenger
            enableComboBoxMessenger();

            // Process to delete the selected row.
            dataGridView.Rows.RemoveAt(dataGridView.CurrentRow.Index);

            // Clear Data Grid View Selection.
            dataGridView.ClearSelection();
            if (comboBoxTransactionType.SelectedValue != null) comboBoxTransactionType_SelectedIndexChanged(null, null);

            // Disable Button to prevent further action.
            buttonDelete.Enabled = false;
        }

        // Data Grid View
        private void dataGridView_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            buttonDelete.Enabled = dataGridView.Rows.Count > 0 && e.RowIndex == dataGridView.Rows.Count - 1;
        }
        private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == -1 || e.RowIndex == -1) return;

            if (Convert.ToBoolean(dataGridView[dataGridViewCheckBoxColumnValidTransaction.Index, e.RowIndex].Value))
            {
                // Changing the Default Row Style.
                dataGridView.Rows[e.RowIndex].DefaultCellStyle = _cellstyleVoid;
            }
            else
            {
                // Changing the Default Row Style.
                dataGridView.Rows[e.RowIndex].DefaultCellStyle = e.RowIndex % 2 == 0 ? _cellstyleNormal : _cellstyleAlternative;
            }

            // Update Quantities and Amounts.
            updateQuantitiesAmounts();
        }
        private void dataGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            // Make the change real
            if (dataGridView.IsCurrentCellDirty) dataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }
        private void dataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            updateQuantitiesAmounts();
        }
        private void dataGridView_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            updateQuantitiesAmounts();
        }
        private void dataGridViewSummary_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            // Reset Variables
            TotalDepositReceiptAmount = 0;
            TotalProofOfPaymentAmount = 0;
            TotalProcessOrderAmount = 0;

            // Calculate Totals
            foreach (DataGridViewRow dataGridViewRow in dataGridViewSummary.Rows)
            {
                TotalDepositReceiptAmount += (decimal)dataGridViewRow.Cells[dEPOSITRECEIPTAMOUNTDataGridViewTextBoxColumn.Index].Value;
                TotalProofOfPaymentAmount += (decimal)dataGridViewRow.Cells[pROOFOFPAYMENTAMOUNTDataGridViewTextBoxColumn.Index].Value;
                TotalProcessOrderAmount += (decimal)dataGridViewRow.Cells[pROCESSORDERAMOUNTDataGridViewTextBoxColumn.Index].Value;
            }
        }

        // Interface
        public void New()
        { }
        public void Save()
        {
            try
            {
                // Begin
                mdiParent.Begin();

                // Set the next Service ID
                int id;

                // Saving the Service
                queriesTableAdapter.InsertServices
                (
                    out id,
                    (byte)numericUpDownNumberOfSamples.Value,
                    (byte)numericUpDownNumberOfDeliveredResults.Value,
                    (byte)numericUpDownNumberOfVisits.Value,
                    (byte)numericUpDownMissingVisits.Value,
                    (byte)numericUpDownKilometers.Value,
                    (byte)numericUpDownGallonsOfFuel.Value,
                    dateTimePickerStartDate.Value,
                    dateTimePickerEndDate.Value,
                    checkBoxAccident.Checked,
                    checkBoxEnoughVials.Checked,
                    checkBoxEnoughBrochures.Checked,
                    checkBoxProperlyUniformed.Checked,
                    comboBoxRoute.Text,
                    comboBoxMessenger.Text,
                    textBoxComments.Text.Trim(),
                    comboBoxOpenByUser.Text,
                    Environment.UserName,
                    Environment.MachineName
                );

                var details = 0;

                // Saving each Detail Service
                foreach (DataGridViewRow dataGridViewRow in dataGridView.Rows)
                {
                    switch ((Global.TransactionTypes)dataGridViewRow.Cells[DataGridViewTextBoxColumnTransactionTypeKey.Index].Value)
                    {
                        case Global.TransactionTypes.DepositReceipt:
                            details += queriesTableAdapter.InsertServiceDetails(Convert.ToInt32(dataGridViewRow.Cells[DataGridViewTextBoxColumnSequence.Index].Value),
                                                                                      (decimal)dataGridViewRow.Cells[dataGridViewTextBoxColumnTransactionAmount.Index].Value, null, 0,
                                                                                      null, 0,
                                                                                      (bool)dataGridViewRow.Cells[dataGridViewCheckBoxColumnValidTransaction.Index].Value,
                                                                                      id);
                            break;
                        case Global.TransactionTypes.ProofOfPayment:
                            details += queriesTableAdapter.InsertServiceDetails(null, 0, Convert.ToInt32(dataGridViewRow.Cells[DataGridViewTextBoxColumnSequence.Index].Value),
                                                                                      (decimal)dataGridViewRow.Cells[dataGridViewTextBoxColumnTransactionAmount.Index].Value, null, 0,
                                                                                      (bool)dataGridViewRow.Cells[dataGridViewCheckBoxColumnValidTransaction.Index].Value,
                                                                                      id);
                            break;
                        case Global.TransactionTypes.ProcessOrder:
                            details += queriesTableAdapter.InsertServiceDetails(null, 0, null, 0, Convert.ToInt32(dataGridViewRow.Cells[DataGridViewTextBoxColumnSequence.Index].Value),
                                                                         (decimal)dataGridViewRow.Cells[dataGridViewTextBoxColumnTransactionAmount.Index].Value,
                                                                         (bool)dataGridViewRow.Cells[dataGridViewCheckBoxColumnValidTransaction.Index].Value,
                                                                         id);
                            break;
                    }
                }

                // Let the user know what's going on.
                mdiParent.SetMessage(MDIParent.MessageType.Successful, details > 0 ? string.Format(Resources.MessageSuccessfulInsertServiceDetail, id, details) : string.Format(Resources.MessageSuccessfulInsertService, id));

                // Clear form
                ClearForm();

                // Log File
            }
            catch (Exception exception)
            {
                // Report Error
                Utilities.ExceptionManager(exception);
            }
            finally
            {
                // End
                mdiParent.End();

                // Change the status of the Save Button.
                enableButtonSave();
            }
        }
        public void Print()
        {
            // Print preview form
            mdiParent.toolStripMenuItemPrint.Enabled = mdiParent.toolStripButtonPrint.Enabled = false;

            // Call preview form
            if (dataGridViewSummary.CurrentRow == null) return;

            FormPrintPreview formPrintPreview = new FormPrintPreview
            (
                this,
                (int)dataGridViewSummary[iDDataGridViewTextBoxColumn.Index, dataGridViewSummary.CurrentRow.Index].Value,
                (DateTime)dataGridViewSummary[sTARTDATEDataGridViewTextBoxColumn.Index, dataGridViewSummary.CurrentRow.Index].Value,
                (DateTime)dataGridViewSummary[eNDDATEDataGridViewTextBoxColumn.Index, dataGridViewSummary.CurrentRow.Index].Value,
                FormPrintPreview.ReportTypes.Services,
                dataGridViewSummary[dEPOSITRECEIPTAMOUNTDataGridViewTextBoxColumn.Index, dataGridViewSummary.CurrentRow.Index].Value.ToString(),
                dataGridViewSummary[pROOFOFPAYMENTAMOUNTDataGridViewTextBoxColumn.Index, dataGridViewSummary.CurrentRow.Index].Value.ToString(),
                dataGridViewSummary[pROCESSORDERAMOUNTDataGridViewTextBoxColumn.Index, dataGridViewSummary.CurrentRow.Index].Value.ToString(),
                dataGridViewSummary[mESSENGERIDDataGridViewTextBoxColumn.Index, dataGridViewSummary.CurrentRow.Index].Value.ToString(),
                dataGridViewSummary[cOMMENTSDataGridViewTextBoxColumn.Index, dataGridViewSummary.CurrentRow.Index].Value.ToString()
            ) { MdiParent = MdiParent, WindowState = FormWindowState.Maximized };

            formPrintPreview.Show();
        }
        public void SetControlBox()
        {
            // Toolbar button
            mdiParent.toolStripMenuItemClear.Enabled = mdiParent.toolStripButtonClear.Enabled = true;
            mdiParent.toolStripMenuItemModeI.Visible = true;
            mdiParent.toolStripMenuItemModeII.Visible = true;
            mdiParent.toolStripMenuItemModeIII.Visible = true;
            mdiParent.toolStripMenuItemModeI.Checked = true;

            enableButtonSave();

            // Hooking up the binding source.
            mdiParent.toolStripMenu.BindingSource = sPSERVICESSELECTBindingSource;
        }
        public void ClearFilter()
        {
            // Reset each control

            // Call method
            refreshServices();
        }
        public void ClearForm()
        {
            // Reset Variables
            DepositReceiptAmount = 0;
            ProofOfPaymentAmount = 0;
            ProcessOrderAmount = 0;
            DepositReceiptQuantity = 0;
            ProofOfPaymentQuantity = 0;
            ProcessOrderQuantity = 0;

            // Clear Data Grid View
            dataGridView.Rows.Clear();

            // Clear Date Time Pickers
            dateTimePickerStartDate.Value = DateTime.Now.AddHours(-1);
            dateTimePickerEndDate.Value = DateTime.Now;

            // Clear selection on Combo Boxes.
            comboBoxMessenger.SelectedIndex = -1;
            comboBoxTransactionType.SelectedIndex = -1;
            comboBoxRoute.SelectedIndex = -1;
            comboBoxMessenger.Enabled = true;

            // Clear Number Up Downs
            numericUpDownNumberOfVisits.Value = numericUpDownNumberOfVisits.Minimum;
            numericUpDownNumberOfSamples.Value = numericUpDownNumberOfSamples.Minimum;
            numericUpDownNumberOfDeliveredResults.Value = numericUpDownNumberOfDeliveredResults.Minimum;
            numericUpDownMissingVisits.Value = numericUpDownMissingVisits.Minimum;
            numericUpDownKilometers.Value = numericUpDownKilometers.Minimum;
            numericUpDownGallonsOfFuel.Value = numericUpDownGallonsOfFuel.Minimum;

            // Clear CheckBoxes
            checkBoxAccident.Checked = checkBoxEnoughVials.Checked = checkBoxEnoughBrochures.Checked = checkBoxProperlyUniformed.Checked = false;

            // Group Box
            groupBoxInputControl.Enabled = false;

            // Clear Text Boxes
            textBoxComments.Text = string.Empty;

            // Refresh Services
            refreshServices();

            // Set Focus
            comboBoxMessenger.Focus();
        }
        public void ChangeFormView(Global.FormViewModes mode)
        {
            switch (mode)
            {
                case Global.FormViewModes.ModeI:
                    splitContainer.Panel1Collapsed = false;
                    splitContainer.Panel2Collapsed = false;
                    break;
                case Global.FormViewModes.ModeII:
                    splitContainer.Panel1Collapsed = false;
                    splitContainer.Panel2Collapsed = true;
                    break;
                case Global.FormViewModes.ModeIII:
                    splitContainer.Panel1Collapsed = true;
                    splitContainer.Panel2Collapsed = false;
                    break;
            }
        }
        public void EnablePrintButton()
        {
            // Enable Logic
            mdiParent.toolStripButtonPrint.Enabled = mdiParent.toolStripMenuItemPrint.Enabled = !dataGridViewSummary.Rows.Count.Equals(0);
        }
        public void Export()
        {
        }

        // General Purpose Functions
        private void refreshServices()
        {
            try
            {
                // Start process
                mdiParent.Begin();

                // Declare Local Variables
                DateTime? startDate, endDate;

                // Initializing Start and End Date variables.
                if (dateTimePickerFilterStart.Checked) startDate = dateTimePickerFilterStart.Value; else startDate = null;
                if (dateTimePickerFilterEnd.Checked) endDate = dateTimePickerFilterEnd.Value; else endDate = null;

                // Populate Grid
                var count = sP_SERVICES_SELECTTableAdapter.Fill(dataSetSGLL.SP_SERVICES_SELECT, startDate, endDate, string.IsNullOrWhiteSpace(comboBoxFilterMessenger.Text) ? null : comboBoxFilterMessenger.Text.Replace(" ", string.Empty));
                labelGeneralTotal.Text = count > 0 ? string.Format(Resources.labelGeneralTotal, count) : Resources.labelGeneralTotalEmpty;

                // Enable Print Button
                EnablePrintButton();

                // Reset Status Bar
                mdiParent.SetMessage();
            }
            catch (Exception exception)
            {
                // Report Error
                Utilities.ExceptionManager(exception);
            }
            finally
            {
                // End process
                mdiParent.End();
            }
        }
        private void enableButtonSave()
        {
            // Enable Logic
            mdiParent.toolStripButtonSave.Enabled = mdiParent.toolStripMenuItemSave.Enabled = !comboBoxOpenByUser.SelectedIndex.Equals(-1) && !comboBoxMessenger.SelectedIndex.Equals(-1) && !comboBoxRoute.SelectedIndex.Equals(-1);
        }
        private void enableComboBoxMessenger()
        {
            // Change State of Messenger Combo Box.
            comboBoxMessenger.Enabled = comboBoxTransactionType.SelectedIndex.Equals(-1) && (DepositReceiptQuantity + ProofOfPaymentQuantity + ProcessOrderQuantity) == 0;
        }
        private void updateSequences(string messengerID, Global.TransactionTypes transactionType, Mode mode)
        {
            switch (transactionType)
            {
                case Global.TransactionTypes.DepositReceipt:
                    queriesTableAdapter.UpdateSequenceDepositReceipt((int)mode, messengerID);
                    break;
                case Global.TransactionTypes.ProofOfPayment:
                    queriesTableAdapter.UpdateSequenceProofOfPayment((int)mode, messengerID);
                    break;
                case Global.TransactionTypes.ProcessOrder:
                    queriesTableAdapter.UpdateSequenceProcessOrder((int)mode, messengerID);
                    break;
            }
        }
        private void updateQuantitiesAmounts()
        {
            // Reset Variables
            DepositReceiptQuantity = 0;
            DepositReceiptAmount = 0;
            ProofOfPaymentQuantity = 0;
            ProofOfPaymentAmount = 0;
            ProcessOrderQuantity = 0;
            ProcessOrderAmount = 0;

            // Recalculate all the values.
            foreach (DataGridViewRow dataGridViewRow in dataGridView.Rows)
            {
                switch ((Global.TransactionTypes)dataGridViewRow.Cells[DataGridViewTextBoxColumnTransactionTypeKey.Index].Value)
                {
                    case Global.TransactionTypes.DepositReceipt:
                        DepositReceiptQuantity++;
                        if (!(bool)dataGridViewRow.Cells[dataGridViewCheckBoxColumnValidTransaction.Index].Value) DepositReceiptAmount += (decimal)dataGridViewRow.Cells[dataGridViewTextBoxColumnTransactionAmount.Index].Value;
                        break;
                    case Global.TransactionTypes.ProofOfPayment:
                        ProofOfPaymentQuantity++;
                        if (!(bool)dataGridViewRow.Cells[dataGridViewCheckBoxColumnValidTransaction.Index].Value) ProofOfPaymentAmount += (decimal)dataGridViewRow.Cells[dataGridViewTextBoxColumnTransactionAmount.Index].Value;
                        break;
                    case Global.TransactionTypes.ProcessOrder:
                        ProcessOrderQuantity++;
                        if (!(bool)dataGridViewRow.Cells[dataGridViewCheckBoxColumnValidTransaction.Index].Value) ProcessOrderAmount += (decimal)dataGridViewRow.Cells[dataGridViewTextBoxColumnTransactionAmount.Index].Value;
                        break;
                }
            }
        }
    }

    public class TransactionType
    {
        public Global.TransactionTypes Key { get; set; }
        public string Value { get; set; }
    }
}